<?php
/*
Copyright (c) 2010 Luis Sánchez Castellanos (http://iquark.org)
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. Neither the name of copyright holders nor the names of its
   contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL COPYRIGHT HOLDERS OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
 */
/** 
 *	Yet! another login system for CodeIgniter
 *  User controller
 *	@author	Luis Sánchez Castellanos
 */
class User extends Controller {
    function User() {
        parent::Controller();
	$this->load->library('yalsciLib');
    }
    // function that shows the login page
    function index() {
		// fin de prueba de envio de correo
		$this->load->view('yalsci/user_index');
    }

    // function that receives the login data
    function signin() {
		$this->load->helper(array('form', 'url','cookie'));
		$this->load->library('form_validation');
		$user_id_attribute = $this->config->item('user_id_attribute');
		$name_attribute = $this->config->item('name_attribute');
		$lastname_attribute = $this->config->item('lastname_attribute');
		$useEmailAsUser = $this->config->item('useEmailAsUser');
		$controller = $this->session->userdata('controller');
		
		// Form validation rules
		$this->form_validation->set_rules('password', 'password', 'trim|required|md5');
		if($useEmailAsUser==TRUE) {
			$this->form_validation->set_rules('email', 'email', 'trim|required|valid_email|xss_clean');
		} else {
			$this->form_validation->set_rules('user', 'user', 'trim|required|xss_clean');
		}
		// check the validation
		if ($this->form_validation->run() == FALSE) {
			$this->load->view('yalsci/signin_page');
		}
        else {
            if($useEmailAsUser==TRUE) {
                $user = $this->input->post('email');
            } else {
                $user = $this->input->post('user');
            }
            $this->load->library('yalsciLib');
			
            $userSignIn = $this->yalscilib->checkSignIn($user, $this->input->post('password'));
			// if the user id is negative, there is some error
            if($userSignIn['user_id']<0) {
	            if($userSignIn['user_id']==-2) {
		            $data['message'] = $this->lang->line('error_incorrect_user_pass');
		         
				}
				if($userSignIn['user_id']==-3) {
		            $data['message'] = $this->lang->line('error_inactive_user');
		         
				}
				// @todo count number of tries, 
				// if is greater than the maximum the user can't continue triyng
                $this->load->view('yalsci/signin_page',$data);
            } else {
                // remember function
                $remember = $this->input->post('remember');
                if($remember=='remember') {
                    // @todo remember user: using a cookie
					$cookie = array(
					   'name'   => 'yalsci_remember',
					   'value'  => $userSignIn['user_id'],
					   'expire' => '86500',
					   'domain' =>  base_url(),
					   'path'   => '/',
					   'prefix' => 'pref_',
				   	);

					set_cookie($cookie); 
                } else {
					delete_cookie("yalsci_remember");
				}
                $this->session->set_userdata('user_id',$userSignIn['user_id']);
                $this->session->set_userdata('user_name',$userSignIn['name']);
                $this->session->set_userdata('user_lastname',$userSignIn['lastname']);
                if(!isSet($controller) || $controller=="") {
                    redirect('user/index');
                } else {
                    redirect($controller);
                }
            }
        }
    }

    // function that receives the new user data
    function register() {
        $this->config->load('yalsci');
        // load all variables we need from yalsci's configuration file
		$email_attribute = $this->config->item('email_attribute');
		$username_attribute = $this->config->item('username_attribute');
		$password_attribute = $this->config->item('password_attribute');
		$user_id_attribute = $this->config->item('user_id_attribute');
		$name_attribute = $this->config->item('name_attribute');
		$lastname_attribute = $this->config->item('lastname_attribute');
		$date_creation_attribute = $this->config->item('date_creation_attribute');
		$date_modification_attribute = $this->config->item('date_modification_attribute');
		$activation_key_attribute = $this->config->item('activation_key_attribute');
		$activationOnRegister = $this->config->item('activationOnRegister');
		$disableRegister = $this->config->item('disableRegister');
		$useEmailAsUser = $this->config->item('useEmailAsUser');
        
        if($disableRegister) {
            $data['message'] = $this->lang->line('error_register_disabled');
            $this->load->view('yalsci/signin_page',$data);
        } else {
            $this->load->helper(array('form', 'url'));
            $this->load->library('form_validation');
            $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]|matches[passconf]|md5');
            $this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required');
            $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
            $this->form_validation->set_rules('user', 'Username', 'trim|required');
            
            if($useEmailAsUser==FALSE) {
                $this->form_validation->set_rules('user', 'user', 'trim|required');
            }
            $this->form_validation->set_rules('username', 'Username', 'trim|max_length[0]');
            $data['useEmailAsUser'] = $useEmailAsUser;
            if ($this->form_validation->run() == FALSE) {
                // @todo send a confirmation email, now the user's information is stored into the database directly
                // time mark for spammers
                $this->session->set_userdata('time_mark', time());
                $this->load->view('yalsci/register_page', $data);
	    	} else {
				// check in the time mark
				$max_timemark = $this->config->item('max_timemark');
				if((time()-$this->session->userdata('time_mark'))<$max_timemark) {
					$data['error'] = $this->lang->line('error_timemark');
		       	} else {
					$this->load->library('yalsciLib');
					if($this->input->post('user')!=NULL) {
						$user = $this->input->post('user');
					} else {
						$user = NULL;
					}
					$result=$this->yalscilib->register($this->input->post('email'), $this->input->post('password'), $user);
					if($result['registered']==FALSE) {
						$data['error'] = $result['error'];
					}
		        }
		        if(isSet($data['error'])) {
		            $this->load->view('yalsci/register_page',$data);
		        } else {
		            $this->load->view('yalsci/register_success');
		        }
            }
        }
    }
    // function to destroy the session
    function signout() {
		$this->load->helper(array('url','cookie'));
        $this->session->sess_destroy();
		delete_cookie("yalsci_remember");
        $data['message'] = $this->lang->line('signed_out');
        $this->load->view('yalsci/signin_page',$data);
    }
    // function to reset a forgotten password
    function forgot() {
        // @todo forgotten password's feature
        $this->form_validation->set_rules('email', 'email', 'trim|required|valid_email|xss_clean');
       
        if ($this->form_validation->run() == FALSE) {
			$this->load->view('yalsci/forgot_page');
        }
        else {
			$this->load->library('yalsciLib');
			$this->yalscilib->sendForgotEmail($this->input->post('email'));
			$data['message'] = $this->lang->line('message_reset_password');
			$this->load->view('yalsci/signin_page',$data);
		}
    }
    // function to activate an user
    function activate($key) {
		$data['message']=$this->yalscilib->activate($key);
		echo "activando con la clave $key";
    }
    
    // function to test if you are signed in
    function testlogin() {
		$data['controller'] = $this->session->userdata('controller');
		$this->load->view('yalsci/signin_test',$data);
    }
    
    // function to show the administrator panel
    function admin() {
		$data['controller'] = $this->session->userdata('controller');
		$this->load->view('admin/admin_index',$data);
    }
}

/* End of file User.php */
/* Location: ./system/application/controllers/user.php */
